package com.neusoft.neuiotms.common.utils;

import java.util.Calendar;
import java.util.Date;

public class DateUtil {

    /**
     * 获取任意一天所在周的开始
     *
     * @param anyday
     * @return
     */
    public static Date getStartTimeOfWeek(Date anyday) {
        if (null == anyday) {
            anyday = new Date();
        }
        final Calendar c = Calendar.getInstance();
        c.setTime(anyday);
        c.set(Calendar.HOUR_OF_DAY, 0);
        c.set(Calendar.MINUTE, 0);
        c.set(Calendar.SECOND, 0);
        c.set(Calendar.MILLISECOND, 0);
        final int dayWeek = c.get(Calendar.DAY_OF_WEEK);
        if (1 == dayWeek) {
            c.add(Calendar.DAY_OF_MONTH, -1);
        }
        c.setFirstDayOfWeek(Calendar.MONDAY);
        final int day = c.get(Calendar.DAY_OF_WEEK);
        c.add(Calendar.DATE, c.getFirstDayOfWeek() - day);
        return c.getTime();
    }

    /**
     * 获取任意一天所在周的结束
     *
     * @param anyday
     * @return
     */
    public static Date getEndTimeOfWeek(Date anyday) {
        if (null == anyday) {
            anyday = new Date();
        }
        final Calendar c = Calendar.getInstance();
        c.setTime(anyday);
        c.set(Calendar.HOUR_OF_DAY, 23);
        c.set(Calendar.MINUTE, 59);
        c.set(Calendar.SECOND, 59);
        c.set(Calendar.MILLISECOND, 0);
        final int dayWeek = c.get(Calendar.DAY_OF_WEEK);
        if (1 == dayWeek) {
            c.add(Calendar.DAY_OF_MONTH, -1);
        }
        c.setFirstDayOfWeek(Calendar.MONDAY);
        final int day = c.get(Calendar.DAY_OF_WEEK);
        c.add(Calendar.DATE, (c.getFirstDayOfWeek() - day) + 6);
        return c.getTime();
    }
}
